package com.py.ssh;

import java.util.Properties;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class SSHTunnelConnectPro {
	private String[] strSshUser = new String[]{"sf","lbs","lbs"}; // SSH loging username
	private String[] strSshPassword =new String[]{ "test","etest","test"}; // SSH login password
	private String[] strSshHost =new String[]{ "iip","ip1","ip3"}; // hostname or ip or SSH server
	private int[] nRemotePort = new int[]{3306,3306,3306}; // remote port number of your database
	private int nSshPort = 22; // remote SSH host port number
	
	private int[] nLocalPort =new int[]{ 3366,6666,7366}; // local port number use to bind SSH tunnel
	
	public void connect() {
		try {
			// hostname or ip of your database server
			String [] strRemoteHost = new String[]{"local.mysql.rds.aliyuncs.com","local.mysql.rds.aliyuncs.com","local"};

			int k = 0;
			for (String remoteHost : strRemoteHost) {
				
				this.doSshTunnel(strSshUser[k], strSshPassword[k], strSshHost[k],
						nSshPort, remoteHost, nLocalPort[k], nRemotePort[k]);
				System.out.println("you can start your businese");
				
				k++;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	
	private Session doSshTunnel(String strSshUser, String strSshPassword,
			String strSshHost, int nSshPort, String strRemoteHost,
			int nLocalPort, int nRemotePort) throws JSchException {
		final JSch jsch = new JSch();
		Session session = jsch.getSession(strSshUser, strSshHost, 22);
		session.setPassword(strSshPassword);

		final Properties config = new Properties();
		config.put("StrictHostKeyChecking", "no");
		session.setConfig(config);

		session.connect();
		System.out.println("Connected");
		int assinged_port = session.setPortForwardingL(nLocalPort,
				strRemoteHost, nRemotePort);
		System.out.println(strSshUser+ "  localhost:" + assinged_port + " -> "
				+ strRemoteHost + ":" + nRemotePort);
		System.out.println("Port Forwarded");
		
		return session;
	}
	
	
	public static void main(String[] args) {
		SSHTunnelConnectPro conn = new SSHTunnelConnectPro();
		conn.connect();
	}
}
